package com.itec.learn.java.producerconsumer;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * @author chenyiqun
 */
public class PlateEgg {

    public static void main(String[] args) {

        Plate p = new Plate();

        for (int i = 0; i < 10; i++) {
            Thread putThread = new Thread(new PutThread(p));
            Thread getThread = new Thread(new GetThread(p));
            putThread.start();
            getThread.start();
        }
        
    }

}


/**
 * 竞争资源
 * */
class Plate{

    private LinkedList<Object> eggs = new LinkedList<Object>();

    public Object get(){
        if (eggs.size()>0){
            return eggs.pop();
        }
        return null;
    }

    public void put(Object egg){
        eggs.push(egg);
    }

    public boolean isEmpty(){
        return eggs.size() == 0;
    }
}

class PutThread implements Runnable{
    private final Plate plate;

    PutThread(Plate plate){
        this.plate = plate;
    }
    @Override
    public void run() {
        synchronized (plate){
            if (!plate.isEmpty()){
                try {
                    plate.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            plate.put("E");
            System.out.println("放鸡蛋：E");
            plate.notifyAll();
        }
    }
}

class GetThread implements Runnable{
    private final Plate plate;

    GetThread(Plate plate){
        this.plate = plate;
    }
    @Override
    public void run() {
        synchronized (plate){
            if (plate.isEmpty()){
                try {
                    plate.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            Object egg = plate.get();
            System.out.println("拿鸡蛋：" + egg);
            plate.notifyAll();
        }
    }
}
